import BleManager from '../../services/bleManager.js';
// 增强的数据转换工具
const dataUtils = {
  // ArrayBuffer 转 16进制字符串
  ab2hex: function(buffer) {
    if (!buffer) return '';
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join('');
  },

  // 16进制字符串转UTF-8字符串（解决中文乱码）
  hex2utf8: function(hex) {
    if (!hex) return '';
    try {
      // 将16进制字符串转换为字节数组
      const bytes = [];
      for (let i = 0; i < hex.length; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16));
      }
      
      // 使用TextDecoder解码UTF-8（推荐方式）
      if (typeof TextDecoder !== 'undefined') {
        try {
          const decoder = new TextDecoder('utf-8');
          return decoder.decode(new Uint8Array(bytes));
        } catch (e) {
          console.log('TextDecoder失败，使用备选方案');
        }
      }
      
      // 备选方案：手动解码UTF-8
      let result = '';
      let i = 0;
      while (i < bytes.length) {
        const byte = bytes[i];
        
        if (byte < 0x80) {
          // 单字节字符 (0xxxxxxx)
          result += String.fromCharCode(byte);
          i += 1;
        } else if (byte >= 0xC0 && byte < 0xE0) {
          // 双字节字符 (110xxxxx 10xxxxxx)
          if (i + 1 < bytes.length) {
            const byte2 = bytes[i + 1];
            const codePoint = ((byte & 0x1F) << 6) | (byte2 & 0x3F);
            result += String.fromCharCode(codePoint);
            i += 2;
          } else {
            // 数据不完整，跳过
            i += 1;
          }
        } else if (byte >= 0xE0 && byte < 0xF0) {
          // 三字节字符 (1110xxxx 10xxxxxx 10xxxxxx) - 中文常用
          if (i + 2 < bytes.length) {
            const byte2 = bytes[i + 1];
            const byte3 = bytes[i + 2];
            const codePoint = ((byte & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F);
            result += String.fromCharCode(codePoint);
            i += 3;
          } else {
            i += 1;
          }
        } else {
          // 四字节字符或无效，跳过
          i += 1;
        }
      }
      return result;
    } catch (error) {
      console.error('UTF-8解码错误:', error);
      return '';
    }
  },

  // 字符串转ArrayBuffer（确保UTF-8编码）
  str2ab: function(str) {
    try {
      // 使用TextEncoder（推荐）
      if (typeof TextEncoder !== 'undefined') {
        const encoder = new TextEncoder();
        return encoder.encode(str).buffer;
      }
      
      // 备选方案：手动编码
      const utf8Bytes = [];
      for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i);
        
        if (charCode < 0x80) {
          // 单字节
          utf8Bytes.push(charCode);
        } else if (charCode < 0x800) {
          // 双字节
          utf8Bytes.push(0xC0 | (charCode >> 6));
          utf8Bytes.push(0x80 | (charCode & 0x3F));
        } else if (charCode < 0x10000) {
          // 三字节（包括大部分中文）
          utf8Bytes.push(0xE0 | (charCode >> 12));
          utf8Bytes.push(0x80 | ((charCode >> 6) & 0x3F));
          utf8Bytes.push(0x80 | (charCode & 0x3F));
        } else {
          // 四字节
          utf8Bytes.push(0xF0 | (charCode >> 18));
          utf8Bytes.push(0x80 | ((charCode >> 12) & 0x3F));
          utf8Bytes.push(0x80 | ((charCode >> 6) & 0x3F));
          utf8Bytes.push(0x80 | (charCode & 0x3F));
        }
      }
      
      const buffer = new ArrayBuffer(utf8Bytes.length);
      const dataView = new Uint8Array(buffer);
      for (let i = 0; i < utf8Bytes.length; i++) {
        dataView[i] = utf8Bytes[i];
      }
      return buffer;
    } catch (error) {
      console.error('字符串转ArrayBuffer错误:', error);
      // 回退方案：简单ASCII编码
      const buffer = new ArrayBuffer(str.length);
      const dataView = new Uint8Array(buffer);
      for (let i = 0; i < str.length; i++) {
        dataView[i] = str.charCodeAt(i) & 0xFF;
      }
      return buffer;
    }
  }
};
Page({
  data: {
    adapterAvailable: false,
    connected: false,
    devices: [],
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    deviceName: '',
    deviceState: '未知',
    logs: []
  },

  onLoad() {
    this.initBluetooth();
  },

  // 初始化蓝牙适配器
  initBluetooth() {
    const that = this;
    wx.openBluetoothAdapter({
      success: (res) => {
        that.addLog('蓝牙适配器初始化成功');
        that.setData({ adapterAvailable: true });
        that.listenForDevices();
      },
      fail: (err) => {
        that.addLog('蓝牙适配器初始化失败: ' + JSON.stringify(err));
        if (err.errCode === 10001) {
          wx.showModal({
            title: '提示',
            content: '请开启手机蓝牙功能',
            showCancel: false
          });
        }
      }
    });
  },

  // 监听蓝牙适配器状态
  onBluetoothAdapterStateChange() {
    wx.onBluetoothAdapterStateChange((res) => {
      this.addLog('蓝牙适配器状态变化: ' + JSON.stringify(res));
    });
  },

  // 开始搜索设备
  startSearch() {
    const that = this;
    that.addLog('开始搜索设备...');
    
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        that.addLog('设备搜索已启动');
      },
      fail: (err) => {
        that.addLog('设备搜索启动失败: ' + JSON.stringify(err));
      }
    });
  },

  // 停止搜索设备
  stopSearch() {
    const that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        that.addLog('设备搜索已停止');
      }
    });
  },

  // 监听发现设备
  listenForDevices() {
    const that = this;
    wx.onBluetoothDeviceFound((res) => {
      const devices = res.devices.filter(device => 
        device.name && (device.name.includes('Test') || device.localName.includes('Test'))
      );
      
      if (devices.length > 0) {
        that.setData({
          devices: that.data.devices.concat(devices)
        });
        that.addLog(`发现设备: ${devices[0].name}`);
      }
    });
  },

  // 连接设备
  connectDevice(e) {
    const device = e.currentTarget.dataset.device;
    const that = this;
    
    that.addLog(`正在连接设备: ${device.name}`);
    console.log("正在连接设备",new Date())
    wx.createBLEConnection({
      deviceId: device.deviceId,
      success: (res) => {
        console.log("设备连接成功",new Date())
        that.addLog('设备连接成功');
        that.setData({
          connected: true,
          deviceId: device.deviceId,
          deviceName: device.name || 'ESP32设备'
        });
        
        // 获取服务
        that.getServices(device.deviceId);
      },
      fail: (err) => {
        that.addLog('设备连接失败: ' + JSON.stringify(err));
      }
    });
  },

  // 获取蓝牙服务
  getServices(deviceId) {
    const that = this;
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: (res) => {
        console.log("获取服务完成",new Date())
        that.addLog('获取服务成功, 共 ' + res.services.length + ' 个服务');
        console.log(res.services)
        // 查找自定义服务
        const targetService = res.services.find(service => {
          // 这里使用ESP32端设置的服务UUID
          return service.uuid.indexOf('FFF0') !== -1;
        });
        
        if (targetService) {
          that.setData({ serviceId: targetService.uuid });
          that.getCharacteristics(deviceId, targetService.uuid);
        } else {
          that.addLog('未找到目标服务');
        }
      },
      fail: (err) => {
        that.addLog('获取服务失败: ' + JSON.stringify(err));
      }
    });
  },

  // 获取特征值
  getCharacteristics(deviceId, serviceId) {
    const that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: (res) => {
        that.addLog('获取特征值成功, 共 ' + res.characteristics.length + ' 个特征值');
        console.log(res.characteristics)
        // 查找读写特征值
        res.characteristics.forEach(characteristic => {
          const properties = characteristic.properties;
          
          if (properties.write) {
            that.setData({ writeCharacteristicId: characteristic.uuid });
          }
          
          if (properties.read) {
            that.setData({ readCharacteristicId: characteristic.uuid });
          }
          
          if (properties.notify || properties.indicate) {
            // 启用通知
            that.enableNotify(deviceId, serviceId, characteristic.uuid);
          }
        });
        console.log("获取特征完成",new Date())
      },
      fail: (err) => {
        that.addLog('获取特征值失败: ' + JSON.stringify(err));
      }
    });
  },

  // 启用特征值通知
  enableNotify(deviceId, serviceId, characteristicId) {
    const that = this;
    wx.notifyBLECharacteristicValueChange({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      state: true,
      success: (res) => {
        that.addLog('启用通知成功');
        that.setData({ characteristicId: characteristicId });
        
        // 监听特征值变化
        that.onCharacteristicValueChange();
      },
      fail: (err) => {
        that.addLog('启用通知失败: ' + JSON.stringify(err));
      }
    });
  },

  // 监听特征值变化（接收数据）
  onCharacteristicValueChange() {
    const that = this;
    wx.onBLECharacteristicValueChange((res) => {
      // 原始十六进制数据
    const hexData = dataUtils.ab2hex(res.value);
    console.log(new Date())
    that.addLog('原始十六进制数据: ' + hexData);
    
    
    // 转换为可读字符串
    const readableData = dataUtils.hex2utf8(hexData);
    that.addLog('转换后可读数据: ' + readableData);
      that.processReceivedData(readableData);
    });
  },

  // 处理接收到的数据
  processReceivedData(data) {
    const that = this;
    // 根据ESP32发送的数据格式解析设备状态
    if (data.includes('STATUS:')) {
      const status = data.split(':')[1];
      that.setData({ deviceState: status });
      that.addLog('设备状态更新: ' + status);
    }
  },

  // 发送命令到ESP32
  sendCommand(e) {
    console.log(new Date())
    const command = e.currentTarget.dataset.command;
    const that = this;
    
    if (!that.data.connected) {
      that.addLog('设备未连接');
      return;
    }
    
    const buffer = that.str2ab(command);
    
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.writeCharacteristicId,
      value: buffer,
      success: (res) => {
        
        that.addLog('命令发送成功: ' + command);
      },
      fail: (err) => {
        that.addLog('命令发送失败: ' + JSON.stringify(err));
      }
    });
  },

  // 获取设备状态
  getDeviceStatus() {
    this.sendCommand({ currentTarget: { dataset: { command: 'GET_STATUS' } } });
  },

  // 断开连接
  disconnect() {
    const that = this;
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: (res) => {
        that.addLog('设备已断开');
        that.resetConnection();
      },
      fail: (err) => {
        that.addLog('断开连接失败: ' + JSON.stringify(err));
      }
    });
  },

  // 重置连接状态
  resetConnection() {
    this.setData({
      connected: false,
      deviceId: '',
      serviceId: '',
      characteristicId: '',
      deviceName: '',
      deviceState: '未知'
    });
  },

  // 添加日志
  addLog(message) {
    const timestamp = new Date().toLocaleTimeString();
    const newLog = `[${timestamp}] ${message}`;
    const logs = [newLog, ...this.data.logs.slice(0, 19)]; // 保持最新20条日志
    
    this.setData({ logs: logs });
    console.log(message);
  },

  // 工具函数：字符串转ArrayBuffer
  str2ab(str) {
    const buffer = new ArrayBuffer(str.length);
    const dataView = new Uint8Array(buffer);
    for (let i = 0; i < str.length; i++) {
      dataView[i] = str.charCodeAt(i);
    }
    return buffer;
  },

  // 工具函数：ArrayBuffer转16进制字符串
  ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },

  onUnload() {
    if (this.data.connected) {
      this.disconnect();
    }
    this.stopSearch();
  }
});